package sub

import (
	"fmt"
	"quipus/cmd/qpc/sub"
	v1pb "quipus/proto/gen/api/v1"
	"strings"

	"github.com/spf13/cobra"
)

var (
	name     string
	api      string
	url      string
	authinfo []string
)

func init() {
	createCmd.PersistentFlags().StringVarP(&name, "name", "n", "", "provider unique name for llm provider entity")
	createCmd.PersistentFlags().StringVarP(&api, "api", "", "", "the api name for the service provider")
	createCmd.PersistentFlags().StringVar(&url, "url", "", "the service url for service provider")
	createCmd.PersistentFlags().StringSliceVarP(&authinfo, "auth", "a", []string{}, "the auth info for accessing the service provider")

	providerCmd.AddCommand(createCmd)
}

var createCmd = &cobra.Command{
	Use:   "create",
	Short: "Run the cmd to create llm provider",
	RunE: func(cmd *cobra.Command, args []string) error {
		qconn, e := sub.NewGrpcConnect(sub.QpConfig.QPAddress)
		if e != nil {
			return e
		}

		qclient := v1pb.NewLLMServiceClient(qconn)
		ctxWithToken := sub.NewCtxWithToken(sub.QpConfig.Token)
		in := &v1pb.CreateLLMProviderRequest{Name: name, ApiName: api, AccessUrl: url}
		if len(authinfo) > 0 {
			authMap := make(map[string]string)
			for _, auth := range authinfo {
				a := strings.Split(auth, "=")
				if len(a) == 2 {
					authMap[a[0]] = a[1]
				}
			}
			in.AuthInfo = authMap
		}
		rsp, err := qclient.CreateLLMProvider(ctxWithToken, in)
		if err != nil {
			return err
		}
		fmt.Print(rsp)
		return nil
	},
}
